<?php
// +---------------------------------------------------------------------+
// | OneBase    | [ WE CAN DO IT JUST THINK ]                            |
// +---------------------------------------------------------------------+
// | Licensed   | http://www.apache.org/licenses/LICENSE-2.0 )           |
// +---------------------------------------------------------------------+
// | Author     | Bigotry <3162875@qq.com>                               |
// +---------------------------------------------------------------------+
// | Repository | https://gitee.com/Bigotry/OneBase                      |
// +---------------------------------------------------------------------+

namespace app\admin\logic;

use app\common\model\UserAccount;

/**
 * 管理员逻辑
 */
class Admin extends AdminBase
{

    /**
     * 获取管理员信息
     */
    public function getMemberInfo($where = [], $field = true)
    {

        $info = $this->modelMember->getInfo($where, $field);

        $info['leader_nickname'] = $this->modelMember->getValue(['id' => $info['leader_id']], 'nickname');

        return $info;
    }

    /**
     * 获取管理员列表
     */
    public function getMemberList($data = [], $field = 'm.*,b.nickname as leader_nickname', $order = '', $paginate = DB_LIST_ROWS)
    {
        $where = $where1 = [];
        if (!empty($data['date1'])) {
            if (!empty($data['date2'])) {
                $where['a.create_time'] = ['between', [strtotime($data['date1'] . ' 00:00:00'), strtotime($data['date2'] . ' 23:59:59')]];
            } else {
                $where['a.create_time'] = ['between', [strtotime($data['date1'] . ' 00:00:00'), time()]];
            }
        }
        if (!empty($data['uid'])) {
            $where['a.id'] = $data['uid'];
        }
        if (!empty($data['username'])) {
            $where['a.username'] = $data['username'];
        }
        if (!empty($data['mobile'])) {
            $where['a.mobile'] = $data['mobile'];
        }
        if (!empty($data['leader_id']) && $member=$this->modelMember->getInfo(['mobile'=>$data['leader_id']])) {
            $where1['b.leader_id'] = $data['leader_id'];
            $where['a.id'] =0;
        }

        $where['a.status'] =1;
        $where['a.is_inside'] =1;
        if (!empty($where1)) {

            $list = $this->modelMember->alias('a')->join('__MEMBER__ b' ,'a.leader_id = b.id')->where($where)->order($order)->paginate($paginate, false, ['query' => $data]);
        } else {

            $list = $this->modelMember->alias('a')->where($where)->order($order)->paginate($paginate, false, ['query' => $data]);
        }
        return $list;

    }

    /**
     * 导出管理员列表
     */
    public function exportMemberList($where = [], $field = 'm.*,b.nickname as leader_nickname', $order = '')
    {

        $list = $this->getMemberList($where, $field, $order, false);

        $titles = "昵称,用户名,邮箱,手机,注册时间,上级";
        $keys = "nickname,username,email,mobile,create_time,leader_nickname";

        action_log('导出', '导出管理员列表');

        export_excel($titles, $keys, $list, '管理员列表');
    }

    /**
     * 获取管理员列表搜索条件
     */
    public function getWhere($data = [])
    {

        $where = [];

        !empty($data['search_data']) && $where['m.nickname|m.username|m.email|m.mobile'] = ['like', '%' . $data['search_data'] . '%'];

        if (!is_administrator()) {

            $member = session('member_info');

            if ($member['is_share_member']) {

                $ids = $this->getInheritMemberIds(MEMBER_ID);

                $ids[] = MEMBER_ID;

                $where['m.leader_id'] = ['in', $ids];

            } else {

                $where['m.leader_id'] = MEMBER_ID;
            }
        }

        return $where;
    }

    /**
     * 获取存在继承关系的管理员ids
     */
    public function getInheritMemberIds($id = 0, $data = [])
    {

        $member_id = $this->modelMember->getValue(['id' => $id, 'is_share_member' => DATA_NORMAL], 'leader_id');

        if (empty($member_id)) {

            return $data;
        } else {

            $data[] = $member_id;

            return $this->getInheritMemberIds($member_id, $data);
        }
    }

    /**
     * 获取管理员的所有下级管理员
     */
    public function getSubMemberIds($id = 0, $data = [])
    {

        $member_list = $this->modelMember->getList(['leader_id' => $id], 'id', 'id asc', false);

        foreach ($member_list as $v) {

            if (!empty($v['id'])) {

                $data[] = $v['id'];

                $data = array_unique(array_merge($data, $this->getSubMemberIds($v['id'], $data)));
            }

            continue;
        }

        return $data;
    }

    /**
     * 管理员添加到用户组
     */
    public function addToGroup($data = [])
    {

        $url = url('memberList');

        if (SYS_ADMINISTRATOR_ID == $data['id']) {

            return [RESULT_ERROR, '天神不能授权哦~', $url];
        }

        $where = ['member_id' => ['in', $data['id']]];

        $this->modelAuthGroupAccess->deleteInfo($where, true);

        if (empty($data['group_id'])) {

            return [RESULT_SUCCESS, '管理员授权成功', $url];
        }

        $add_data = [];

        foreach ($data['group_id'] as $group_id) {

            $add_data[] = ['member_id' => $data['id'], 'group_id' => $group_id];
        }

        if ($this->modelAuthGroupAccess->setList($add_data)) {

            action_log('授权', '管理员授权，id：' . $data['id']);

            $this->logicAuthGroup->updateSubAuthByMember($data['id']);

            return [RESULT_SUCCESS, '管理员授权成功', $url];
        } else {

            return [RESULT_ERROR, $this->modelAuthGroupAccess->getError()];
        }
    }

    /**
     * 管理员添加
     */
    public function memberAdd($data = [])
    {

        $validate_result = $this->validateMember->scene('add')->check($data);

        if (!$validate_result) {

            return [RESULT_ERROR, $this->validateMember->getError()];
        }

        $url = url('memberList');

        $data['nickname'] = $data['username'];
        $data['leader_id'] = MEMBER_ID;
        $data['is_inside'] = DATA_NORMAL;

        $result = $this->modelMember->setInfo($data);
        UserAccount::addWallet($result);
        $result && action_log('新增', '新增管理员，username：' . $data['username']);

        return $result ? [RESULT_SUCCESS, '管理员添加成功', $url] : [RESULT_ERROR, $this->modelMember->getError()];
    }

    /**
     * 管理员编辑
     */
    public function memberEdit($data = [])
    {

        $validate_result = $this->validateMember->scene('edit')->check($data);

        if (!$validate_result) {

            return [RESULT_ERROR, $this->validateMember->getError()];
        }
     
        $url = url('memberList');
		if(empty($data['password'])){
          unset($data['password']);
        }	
        $result = $this->modelMember->setInfo($data);

        $result && action_log('编辑', '编辑管理员，id：' . $data['id']);

        return $result ? [RESULT_SUCCESS, '管理员编辑成功', $url] : [RESULT_ERROR, $this->modelMember->getError()];
    }

    /**
     * 修改密码
     */
    public function editPassword($data = [])
    {

        $validate_result = $this->validateMember->scene('password')->check($data);

        if (!$validate_result) {

            return [RESULT_ERROR, $this->validateMember->getError()];
        }

        $member = $this->getMemberInfo(['id' => $data['id']]);

        if (data_md5_key($data['old_password']) != $member['password']) {

            return [RESULT_ERROR, '旧密码输入不正确'];
        }

        $data['id'] = MEMBER_ID;

        $url = url('index/index');

        $result = $this->modelMember->setInfo($data);

        $result && action_log('编辑', '管理员密码修改，id：' . $data['id']);

        return $result ? [RESULT_SUCCESS, '密码修改成功', $url] : [RESULT_ERROR, $this->modelMember->getError()];
    }

    /**
     * 设置管理员信息
     */
    public function setMemberValue($where = [], $field = '', $value = '')
    {

        return $this->modelMember->setFieldValue($where, $field, $value);
    }

    /**
     * 管理员删除
     */
    public function memberDel($where = [])
    {

        $url = url('memberList');

        if (SYS_ADMINISTRATOR_ID == $where['id'] || MEMBER_ID == $where['id']) {

            return [RESULT_ERROR, '天神和自己不能删除哦~', $url];
        }

        $result = $this->modelMember->deleteInfo($where);

        $result && action_log('删除', '删除管理员，where：' . http_build_query($where));

        return $result ? [RESULT_SUCCESS, '管理员删除成功', $url] : [RESULT_ERROR, $this->modelMember->getError(), $url];
    }
}
